package com.fannnnn.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fannnnn.system.mapper.MenuMapper;
import com.fannnnn.system.pojo.LoginUser;
import com.fannnnn.system.pojo.User;
import com.fannnnn.system.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * \*  Created with IntelliJ IDEA.
 * \*  @author shensifan
 * \*  Date: 2022/1/26
 * \*  Time: 15:13
 * \*  Description:
 * \
 */

@Service
public class UserDetailServiceImpl implements UserDetailsService {


    @Autowired
    UserServiceImpl userService;

    @Autowired
    MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        /**
         * 从数据库中查询登录的用户
         * */
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",username);
        User user = userService.getOne(wrapper);

        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或密码错误！");
        }

        /**
         * 将用户的信息封装进UserDetail对象当中
         * */
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);

        /**
         * todo 查询用户的权限信息
         * */
        List<String> permission = menuMapper.selectPermsById(user.getId());
        loginUser.setPermissions(permission);

        return loginUser;

    }
}
